package com.lbiuse.wx.api;

import com.lbiuse.wx.bean.user.User;
import com.lbiuse.wx.bean.user.Users;
import com.lbiuse.wx.util.WxHttpUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;



/**
 * 用户API
 * 
 */
public class UserAPI {

	private static Logger logger = Logger.getLogger(UserAPI.class);

	private final static String USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	private final static String UPDATE_USER_REMARK = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=ACCESS_TOKEN";
	private final static String GET_USER_LIST = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN";
	private final static String GET_USER_LIST1 = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";

	/**
	 * 获取用户基本信息
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param openId
	 *            -普通用户的标识，对当前公众号唯一
	 * @return
	 */
	public static User getUserInfo(String appId, String openId) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("获取用户基本信息失败，获取AccessToken失败!");
			return new User(-4, "获取AccessToken失败");
		}
		String url = USER_INFO_URL.replace("ACCESS_TOKEN", token).replace(
				"OPENID", openId);
		try {
			return WxHttpUtils.get(url, User.class);
		} catch (Exception e) {
			logger.error("获取用户基本信息失败, 错误信息：" + e.getMessage());
			return new User(-5, "未知错误！");
		}
	}

	/**
	 * 设置备注名
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param openId
	 *            -用户标识
	 * @param remark
	 *            -新的备注名，长度必须小于30字符
	 * @return
	 */
	public static boolean updateUserRemark(String appId, String openId,
			String remark) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("设置备注名失败，获取AccessToken失败!");
			return false;
		}
		String url = UPDATE_USER_REMARK.replace("ACCESS_TOKEN", token);
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("openid", openId);
			jsonObject.put("remark", remark);
			String json = jsonObject.toString();
			json = WxHttpUtils.post(url, json);
			jsonObject = JSONObject.fromObject(json);
			int errcode = jsonObject.getInt("errcode");
			if (errcode == 0) {
				return true;
			}
			logger.error("设置备注名失败，错误码：" + errcode);
			return false;
		} catch (Exception e) {
			logger.error("设置备注名失败, 错误信息:" + e.getMessage());
			return false;
		}
	}

	/**
	 * 获取关注者列表
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param nextOpenId
	 *            -拉取列表的后一个用户的OPENID
	 * @return
	 */
	public static Users getUserList(String appId, String nextOpenId) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("获取关注者列表失败，获取AccessToken失败!");
			return new Users(-4, "获取AccessToken失败");
		}
		String url = null;
		if (nextOpenId == null) {
			url = GET_USER_LIST.replaceAll("ACCESS_TOKEN", token);
		} else {
			url = GET_USER_LIST1.replaceAll("ACCESS_TOKEN", token).replaceAll(
					"NEXT_OPENID", nextOpenId);
		}
		try {
			String json = WxHttpUtils.get(url);
			JSONObject jsonObject = JSONObject.fromObject(json);
			if (jsonObject.containsKey("errcode")) {
				Integer errcode = jsonObject.getInt("errcode");
				logger.error("获取关注者列表失败，错误码：" + errcode);
				return new Users(errcode, jsonObject.getString("errmsg"));
			}
			int total = jsonObject.getInt("total");
			int count = jsonObject.getInt("count");
			String next_openid = jsonObject.getString("next_openid");
			jsonObject = jsonObject.getJSONObject("data");
			JSONArray jsonArray = jsonObject.getJSONArray("openid");
			String[] openIds = new String[jsonArray.size()];
			int length = jsonArray.size();
			for (int i = 0; i < length; i++) {
				openIds[i] = jsonArray.getString(i);
			}
			Users users = new Users(0, "ok");
			users.setCount(count);
			users.setTotal(total);
			users.setOpenIds(openIds);
			users.setNext_openid(next_openid);
			return users;
		} catch (Exception e) {
			logger.error("获取关注者列表失败, 错误信息:" + e.getMessage());
			return null;
		}
	}

}
